import { Notification } from 'element-ui';

export let ws = null
export let proactivelyClose = false
export let heartCheckTimer = null


export const startWebSocket = () => {
  // ws:// + 请求接口
  const socketUrl = 'ws://127.0.0.1:3000';
  const webSocketServer = new WebSocket(socketUrl);

  webSocketServer.onopen = () => {
    
    console.log(`${new Date().toLocaleString()} >>>>> 连接成功`, ws);
    Notification({
      type: "success",
      title: '成功',
      message: '会话连接成功',
      position: "top-right",
      duration: 3000,
      showClose: true
    });
    // 保存 WebSocket 连接信息
    ws = webSocketServer
    // // 在这里调用 sendWebSocketMessage，确保 ws 已经被正确设置
    // 开始心跳检测
    startHeartCheck()
  };

  webSocketServer.onmessage = (e) => {
    console.log(`${new Date().toLocaleString()} >>>>> 收到消息 ${e.data}`, ws);
    if (e.data !== "pong") {
      Notification({
        type: "success",
        title: '新消息',
        message: e.data,
        position: "top-right",
        duration: 3000,
        showClose: true
      });
    }
  };

  webSocketServer.onclose = () => {
    console.log(`${new Date().toLocaleString()} >>>>> 连接已关闭`);
    // 尝试重新连接 - 前提是非主动关闭
    if (!proactivelyClose) reconnectWebSocket()
  };

  webSocketServer.onerror = (e) => {
    console.log(`${new Date().toLocaleString()} >>>>> 数据传输发生异常`, e);
    Notification({
      type: "error",
      title: '错误',
      message: '会话连接异常，服务已断开',
      position: "top-right",
      duration: 3000,
      showClose: true
    });
  };
}

export const sendWebSocketMessage = (msg) => {
  console.log(`${new Date().toLocaleString()} >>>>> 发送消息：${msg}`);
  ws.send(msg);
}

export const reconnectWebSocket = () => {
  // 尝试主动重连时，不弹出消息
  clearWebSocket(false)
  // 递归调用，一直尝试重连
  setTimeout(() => {
    startWebSocket()
  }, 6000);
}

export const clearWebSocket = (payload) => {
  if (ws && payload) {
    Notification({
      type: "success",
      title: '已关闭连接',
      message: '成功！',
      position: "top-right",
      duration: 3000,
      showClose: true
    });
    ws.close();
    ws = null
    heartCheckTimer = payload ? true : false
  }
}

export const startHeartCheck = () => {
  console.log(`${new Date().toLocaleString()} >>>>> 开始心跳检测`, ws);
  // 清除之前的计时器
  clearHeartCheckTimer()

  // 创建新的计时器
  sendWebSocketMessage('ping')
  const timer = setInterval(() => {
    if (!ws || ws.readyState !== WebSocket.OPEN) {
      console.log(`${new Date().toLocaleString()} >>>>> 心跳检测失败,触发重连`, ws);
      reconnectWebSocket()
    } else {
      console.log(`${new Date().toLocaleString()} >>>>> 心跳正常,继续下一次心跳检测`, ws);
      sendWebSocketMessage('ping')
    }
  }, 1000 * 29);
  heartCheckTimer = timer
}

export const clearHeartCheckTimer = () => {
  const timer = heartCheckTimer;
  timer && clearInterval(timer);
  heartCheckTimer = timer
}